import {defineStore} from 'pinia';
import {Http, Cache, Helper, Msg, Constant} from 'core';
import Base64 from '@/util/base64.js';
const store = {
    id: "user",
    state(){
        return {
            user: {},
			roles: [],
			permissions: []
        }
    },

    getters: {

    },

    actions: {
        setUser(user, roles, permissions) {
            this.user = user;
            this.roles = roles;
            this.permissions = permissions;
        },

		getUser() {
			return Helper.emptyJson(this.user) ? {} : this.user;
		},

		getRole() {
			return Helper.emptyArray(this.roles) ? [] : this.roles;
		},

		hasRole(roleCode) {
        	return Helper.emptyArray(this.roles) ? false : this.roles.indexOf(roleCode) > -1
		},

		async login(username, password) {
			Msg.loading("加载中...")
			Cache.setToken("");
			let {code, message, data} = await Http.post("/oauth2/token", {username: username,
				password: Helper.encryption(password, import.meta.env.VITE_APP_PWD_ENC_KEY),
				grant_type: "password", scope: "server"})
				.addHeaders("Skiptoken", true)
				.addHeaders("Content-type", "application/x-www-form-urlencoded")
				.addHeaders("Authorization", "Basic " + Base64.encoder(import.meta.env.VITE_APP_OAUTH2_PASSWORD_CLIENT))
				.setInterceptor(null, (response) => {
					let res = {};
					if(! Helper.empty(response.code)) {
						res = {code: 500, msg: response.data.msg, data: response.data};
					} else {
						res = {code: 0, msg: "调用成功", data: response.data};
					}
					response.data = res;
				})
			Msg.loading(false);
			if(code == 200) {
				//读取用户信息
				Cache.setToken(data.access_token);
				await this.brief();
				uni.switchTab({url: "index"});
			}
		},

		/**
		 * 绑定
		 * @param code
		 * @returns {Promise<boolean|*>}
		 */
		async bind(authCode) {
			Msg.loading("加载中...")
			let {code, data} = await Http.post("/social/bind", {state: "APP-MNG-ALIPAY", code: authCode})
				.addHeaders("Content-type", "application/x-www-form-urlencoded")
			Msg.loading(false);
			if(code == 200) {
				if(! data) {

					Msg.error("绑定失败");
				}
				return data;
			}

			return false;
		},

		async brief() {
			this.user = {};
			Msg.loading("加载中...");
			let {code, data} = await Http.get("/user/info");
			Msg.loading(false);
			if(code == 200) {
				let user = data.sysUser;
				let roles = data.roles;
				let permissions = data.permissions;
				this.setUser(user, roles, permissions);
			}

			return this.user;
		},

		async check() {
			return await Http.post("/user/check/token").validate(false);
		},

		async submit() {
			return await Http.post("/user/perfect", this.user);
		},

		async logout() {
			await Http.create("/token/logout").setMethod("delete");
		}
    }
}

export default defineStore(store)
